package com.oracle.oa.util;

import java.util.ArrayList;
import java.util.List;

import com.oracle.oa.entity.Fileinfo;


public class Tree {  
    private StringBuffer html = new StringBuffer();  
    private List<Fileinfo> nodes;  
      
    public Tree(List<Fileinfo> nodes){  
        this.nodes = nodes;  
    }  
      
    public String buildTree(){  
        html.append("<ul>");  
        for (Fileinfo node : nodes) {  
            long id = node.getFileid();  
            if (node.getParentid() == 0l) {  
                html.append("\r\n<li id='" + id + "'><a href='/OAProject/file/tree_findChild?fileid="+id+"' target='fileMenu-right' >" +"<img src="+node.getFiletypeinfo().getFiletypeimage()+" width='20px' height='20px' > "+ node.getFilename()+ "</a></li>");  
                build(node);  
            }  
        }  
        html.append("\r\n</ul>");  
        return html.toString();  
    }  
      
    private void build(Fileinfo node){  
        List<Fileinfo> children = getChildren(node);  
        if (!children.isEmpty()) {  
            html.append("\r\n<ul>");  
            for (Fileinfo child : children) {  
                long id = child.getFileid();  
                html.append("\r\n<li id='" + id + "'><a href='/OAProject/file/tree_findChild?fileid="+id+"' target='fileMenu-right' >" +"<img src="+child.getFiletypeinfo().getFiletypeimage()+" width='20px' height='20px'>    "+ child.getFilename()+ "</a></li>");  
                build(child);  
            }  
            html.append("\r\n</ul>");  
        }   
    }  
      
    private List<Fileinfo> getChildren(Fileinfo node){  
        List<Fileinfo> children = new ArrayList<Fileinfo>();  
        long id = node.getFileid();  
        for (Fileinfo child : nodes) {  
            if (id==child.getParentid()) {  
                children.add(child);  
            }  
        }  
        return children;  
    }  
}  
